package max.array;

public class BigMSum {

	public static void main(String[] args) {
		int[] array = new int[] { 0, -1, 7, 170, 200, 15, 22, -99, 33, 18, -19, -99, 300, -10 };
		int m = 3;
		int result = sum(array, m);
		System.out.println(result);
	}

	/**
	 * 这种方式是错误的。
	 *
	 * @param array
	 * @param m
	 * @return
	 */
	public static int sum(int[] array, int m) {
		if (array == null || m == 0)
			return Integer.MIN_VALUE;
		if (array.length == 1) {
			return array[0];
		}
		int big = array[0]; // 初始化最大值
		int pointa = 0;// 左界当前位置
		int pointb = 1;// 右界当前位置
		int distance = pointb - pointa + 1; // 左右界中间数字数量
		int flag = 0; // 0 允许右界前进， 1允许左界前进
		int sum = array[pointa] + array[pointb]; // 初始化和
		while (pointb < array.length) {
			big = big < sum ? sum : big;
			if (pointa == array.length - 1) {
				break;
			}
			distance = pointb - pointa + 1;
			if (pointb + 1 < array.length && distance < m && flag == 0) {
				pointb++;
				sum = sum + array[pointb];
			} else if (pointa < pointb) {
				flag = 1;
				pointa++;
				sum = sum - array[pointa - 1];
			} else if (pointb + 1 < array.length && flag == 1 && pointa == pointb) {
				flag = 0;
				pointb++;
				sum = sum + array[pointb];
			}
		}
		return big;
	}

}
